package com.boot.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.boot.filter.*;
import com.boot.realm.MyRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    //DefaultWebSecurityManager 管理主题(用户)
    @Bean
    public DefaultWebSecurityManager manager(@Qualifier("myRealm") MyRealm myRealm){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(myRealm);
        return manager;
    }

    @Bean
    public ShiroFilterFactoryBean filterFactoryBean(@Qualifier("manager") DefaultWebSecurityManager manager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(manager);

        Map<String, Filter> filters = new HashMap<>();
        filters.put("myOncePerRequestFilter",new MyOncePerRequestFilter());
        filters.put("myAdviceFilter",new MyAdviceFilter());
        filters.put("myPathMatchingFilter",new MyPathMatchingFilter());
        filters.put("myAccessControlFilter",new MyAccessControlFilter());
        filters.put("formLoginFilter",new FormLoginFilter());

        factoryBean.setFilters(filters);

        Map<String,String> map = new HashMap<>();
        //authc和user类似 只要认证成功即可
        //anon:匿名可以访问
        map.put("/test","user");
        map.put("/login","anon");
        map.put("/main","authc");
        map.put("/manage","perms[manage,add]");//可以写多个
        map.put("/administrator","roles[administrator]");

        //使用过滤器
        map.put("/myCenter","myOncePerRequestFilter,myAdviceFilter");//myCenter接口 走过滤器myOncePerRequestFilter、myAdviceFilter
        map.put("/myOrder","myAccessControlFilter");

        map.put("/doLogin","formLoginFilter");//所有的URL都走判断

        factoryBean.setFilterChainDefinitionMap(map);

        factoryBean.setLoginUrl("/login");
        factoryBean.setUnauthorizedUrl("/unauth");
        return factoryBean;
    }

    //使用Spring创建bean
    @Bean
    public MyRealm myRealm(){
        return new MyRealm();
    }

    //thymeleaf的shiro标签
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }

}
